import { useState } from 'react'

/**
 *
 * @param {object} items
 * @param {boolean} items.simple 是否仅支持单个字段排序
 * @returns
 */
export default function useTableSortable(options = {}) {
  const { simple = false } = options

  const [cursort, setCursort] = useState({ field: undefined, order: undefined })
  const [sorts, setSorts] = useState([])

  // 排序
  const onTableChange = (pagination, filters, sorter) => {
    console.log('%c Line:143 🍧 sorter', 'color:#ea7e5c', sorter)
    if (sorter.field === undefined && sorts.length === 0) return

    const newSort = { field: sorter.field, order: sorter.order }

    // 仅支持单个字段进行排序
    if (simple) {
      sorter.field ? setSorts([newSort]) : setSorts([])
    } else {
      sorts.length
        ? setSorts((sort) => {
            if (sorter.field === undefined) {
              return sort.filter((item) => item.field !== cursort.field)
            }
            if (sort.some((item) => item.field === sorter.field)) {
              return sort.map((item) => (item.field === sorter.field ? newSort : item))
            }
            return [...sort, newSort]
          })
        : setSorts([newSort])
    }
    setCursort(newSort)
  }

  return {
    cursort,
    sorts,
    setSorts,
    onTableChange,
  }
}
